package com.pan.behavioral.iterator.itr.impl;

import com.pan.behavioral.iterator.itr.MyCollection;
import com.pan.behavioral.iterator.itr.MyIterator;

import java.util.function.Consumer;

public class MyArrList<T> implements MyCollection<T> {

    private T[] arr;

    private int size;

    public MyArrList() {
        this.arr = (T[]) new Object[114];
        size = 0;
    }


    @Override
    public MyIterator<T> iterator() {
        return new ArrListIterator();
    }

    private class ArrListIterator implements  MyIterator<T>{
        int current = 0;
        @Override
        public boolean hasNext() {
            return current<size;
        }
        @Override
        public T next() {
            if (current>=size)throw new RuntimeException("ArrList 越界了");
            return arr[current++];
        }
        @Override
        public void remove() {
            size--;
            for (int i = current; i < size; i++) {
                arr[i] = arr[i+1];
            }
        }
        @Override
        public void forEachRemaining(Consumer action) {
            for (;hasNext();)action.accept(next());
        }
    }

    @Override
    public void add(T element) {
        if (size+1 >= arr.length){
            T[] newArr = (T[]) new Object[arr.length+114];
            for (int i = 0; i < arr.length; i++) {
                newArr[i] = arr[i];
            }
            arr = newArr;
        }
        arr[size++] = element;
    }

    public int size(){
        return size;
    }

}
